package com.whstudio.activity.service;

import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.whstudio.util.mvc.data.sql.CommonSql;
import com.whstudio.util.mvc.data.sql.DatabaseParameter;
import com.whstudio.util.mvc.data.sql.ICommonSql;
import com.whstudio.util.mvc.data.sql.IParameter;
import com.whstudio.util.mvc.data.sql.ICommonSql.SQL_TYPES;
import com.whstudio.util.string.StrUtil;
import com.whstudio.util.string.WhiteSpaceHandler;
import com.whstudio.util.xml.IDocument;

public class Server implements IServer {
	private IDocument document=null;
	public Server(IDocument document){
		this.document=document;
	}
	
	public SQL_TYPES getSqlType(Integer flag){
		switch(flag){
		case 1:return SQL_TYPES.INSERT;
		case 2:return SQL_TYPES.UPDATE;
		case 3:return SQL_TYPES.DELETE;
		case 4:return SQL_TYPES.SELECT;
		default:return SQL_TYPES.UNDEFINED;
		}
	}
	
	/**
	 * 根据一个XML元素生成SQL语句并执行，返回执行结果XML
	 * @return
	 */
	private IDocument executeElement(Element element) throws SQLException{
		String tableString=element.getAttribute("name");
		Integer flag=StrUtil.noeInt(element.getAttribute("flag"), 0);
		SQL_TYPES sqlType=getSqlType(flag);
		if(sqlType.equals(SQL_TYPES.UNDEFINED)){
			return null;
		}
		List<IParameter> parameters=new ArrayList<IParameter>();
		NodeList itemList=element.getElementsByTagName("item");
		for (int i = 0; i < itemList.getLength(); i++) {
			Element itemNode=(Element)itemList.item(i);
			String itemName=itemNode.getAttribute("name");
			String itemString=getCDATASectionString(itemNode);
			if(itemString==null){
				continue;
			}
			IParameter e=new DatabaseParameter(itemName);
			e.setType(Types.VARCHAR);
			e.setValue(itemString);
			parameters.add(e);
		}
		ICommonSql sql=new CommonSql(tableString,sqlType,parameters);
		IDocument resultDocument=sql.getResultDocument();
		return resultDocument;
	}
	
	/**
	 * 提供服务
	 * @throws SQLException 
	 */
	public IDocument doServe() throws SQLException{
		Element element=(Element)(document.getDocumentElement());
		IDocument oneResultDocument=executeElement(element);
		return oneResultDocument;
	}
	
	private String getCDATASectionString(Element itemNode){
		String nodeValue=null;
		NodeList itemList=itemNode.getChildNodes();
		for (int i = 0; i < itemList.getLength(); i++) {
			Node node=itemList.item(i);
			if(node.getNodeType()==Node.CDATA_SECTION_NODE){
				nodeValue=node.getNodeValue();
				break;
			}
		}
		return new WhiteSpaceHandler().bind(nodeValue).toString();
	}
}
